#include "QNBUtls.h"

#include "QNBConstant.h"
#include "QNBUserInfo.h"

#include <QDateTime>
#include <QJsonObject>
#include <QJsonValue>
#include <QDir>

#include <QDebug>

QNBUtls::QNBUtls()
{


}

time_t QNBUtls::curTime()
{
    QDateTime local(QDateTime::currentDateTime());
    time_t curTime = local.toUTC().toTime_t();

    return curTime;
}

QString QNBUtls::getStringValue(QJsonObject& obj, const QString& name, const QString& defVal)
{
    QString strValue = "";
    if(obj.contains(name))
    {
        QJsonValue value = obj.take(name);
        if(value.isString())
        {
            strValue = value.toString(defVal);
            qDebug() <<name<<" = " <<strValue;
        }
    }

    return strValue;
}

QString QNBUtls::getTmpDataDir()
{
    QString strTmp = TMP_DATA_DIR;

    QString strDateTime = QDateTime::currentDateTime().toString("yyyyMMdd");
    strTmp += QDir::separator();
    strTmp += strDateTime;

    if(!QNBUserInfo::getInstance()->mstrIdentify.isEmpty())
    {
        strTmp += QDir::separator();
        strTmp += QNBUserInfo::getInstance()->mstrIdentify;
    }

    QDir dir(strTmp);
    if(!dir.exists()) {
        dir.mkpath(strTmp);
    }

    return strTmp;
}

QString QNBUtls::getAuthDataDir()
{
    QString strTmp = AUTH_DATA_DIR;

    QString strDateTime = QDateTime::currentDateTime().toString("yyyyMMdd");
    strTmp += QDir::separator();
    strTmp += strDateTime;

    if(!QNBUserInfo::getInstance()->mstrIdentify.isEmpty())
    {
        strTmp += QDir::separator();
        strTmp += QNBUserInfo::getInstance()->mstrIdentify;
    }

    QDir dir(strTmp);
    if(!dir.exists()) {
        dir.mkpath(strTmp);
    }

    return strTmp;
}


bool QNBUtls::deleteDir(const QString &dirName)
{
    QDir directory(dirName);
    if (!directory.exists())
    {
        return true;
    }

    QString srcPath = QDir::toNativeSeparators(dirName);
    if (!srcPath.endsWith(QDir::separator()))
        srcPath += QDir::separator();

    QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
    bool error = false;
    for (QStringList::size_type i=0; i != fileNames.size(); ++i)
    {
        QString filePath = srcPath + fileNames.at(i);
        QFileInfo fileInfo(filePath);
        if (fileInfo.isFile() || fileInfo.isSymLink())
        {
            QFile::setPermissions(filePath, QFile::WriteOwner);
            if (!QFile::remove(filePath))
            {
                qDebug() << "remove file" << filePath << " faild!";
                error = true;
            }
        }
        else if (fileInfo.isDir())
        {
            if (!deleteDir(filePath))
            {
                error = true;
            }
        }
    }

    if (!directory.rmdir(QDir::toNativeSeparators(directory.path())))
    {
        qDebug() << "remove dir" << directory.path() << " faild!";
        error = true;
    }

    return !error;
}
